package cc.magicjson.example.demo.spark;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MontyHallProblemByXunFei {
    private static final int NUM_DOORS = 3;
    private static final int CAR_DOOR = 2;

    public static void main(String[] args) {
        int numberOfExperiments = 1000000;
        double winRateWhenSwitching = simulate(numberOfExperiments, true);
        System.out.printf("改变选择赢得的概率为： %.2f%%", winRateWhenSwitching * 100);
    }

    private static double simulate(int numberOfExperiments, boolean switchDoors) {
        int wins = 0;
        for (int i = 0; i < numberOfExperiments; i++) {
            if (playGame(switchDoors)) {
                wins++;
            }
        }
        return (double) wins / numberOfExperiments;
    }

    private static boolean playGame(boolean switchDoors) {
        List<Integer> doors = new ArrayList<>();
        for (int i = 0; i < NUM_DOORS; i++) {
            doors.add(i);
        }

        // 主持人打开一个山羊门
        Random random = new Random();
        int goatDoor = random.nextInt(NUM_DOORS);
        while (goatDoor == CAR_DOOR) {
            goatDoor = random.nextInt(NUM_DOORS);
        }
        doors.remove((Integer) goatDoor);

        // 参赛者选择一个门
        int chosenDoor = random.nextInt(doors.size());
        if (switchDoors) {
            // 参赛者改变选择
            chosenDoor = (chosenDoor + 1) % doors.size();
        }

        return chosenDoor == CAR_DOOR;
    }
}
